import cloud from '@lafjs/cloud'
const dbm = cloud.mongo.db
const db = cloud.database();
import { pinyin } from "pinyin-pro";
let dbName = "admin-class-student"

export default async function (ctx: FunctionContext) {
  let data = ctx.body.data
  switch (ctx.body.type) {
    case "orders":
      return await orders()
      break;
    case "add":
      return await add()
      break;
    case "list":
      return await list()
      break;
    case "update":
      return await cloud.utils.updateData(dbName, data)
      break;
    case "del":
      return await cloud.utils.deleteData(dbName, data)
      break;
    case "otherClass"://其他班级
      return await otherClass()
      break;
    case "classStudentCount"://班次有几个未停课的学生
      return await classStudentCount()
      break;
    case "canMoveOtherClass"://是否可以挪动到别的班级
      return await canMoveOtherClass()
      break;
    case "query":
      return await query()
      break;
    case "queryNotSuspended":
      return await queryNotSuspended()
      break;
    case "scoreImport"://成绩导入
      return await scoreImport()
      break;
    case "offline-student-import"://线下学员导入
      return await offlineStudentImport()
      break;
    case "del-offline-student"://线下学员删除
      return await cloud.utils.deleteData("admin-class-offline-student", { _id: data.offlineUserId })
      break;
    case "add-historical-students"://添加历史学员
      return await addHistoricalStudents()
      break;
    default:
      break;
  }

  async function addHistoricalStudents() {
    let { classId, userId } = data
    //拿到班级绑定的课程和开班时间
    let { curriculumId, classOpeningTime } = await cloud.nw.db.findByWhereJson({
      dbName: "admin-class",
      whereJson: { _id: classId },
    });
    //查询开班日期年份内的订单
    let year = cloud.utils.dateTimeFormat(classOpeningTime, "year")
    const startOfYear = new Date(year, 0, 1).getTime(); // 该年份的开始时间戳
    const endOfYear = new Date(year, 11, 31, 23, 59, 59, 999).getTime(); // 该年份的结束时间戳

    let whereJson = {
      _add_time: { $gte: startOfYear, $lt: endOfYear },
      curriculum_id: curriculumId,
      status: { $nin: [0, 6] },
      userId
    }
    let res = await cloud.nw.db.findByWhereJson({
      dbName: "web-order",
      whereJson,
    });
    return cloud.utils.requestReturn({ data: res && res._id ? res._id : "" })
  }

  async function offlineStudentImport() {
    let collectionName = "admin-class-offline-student"
    let { classId, list } = data
    for (let index = 0; index < list.length; index++) {
      const element = list[index];
      let { mobile, identityCard } = element
      element.classId = classId //绑定班级id
      element.userPinyin = pinyin(element.name, { toneType: "none" })
      if (mobile) {
        const count = await dbm.collection(collectionName).countDocuments({ mobile, classId })
        if (count) return cloud.utils.requestReturn({ code: 500, msg: `手机号${mobile}已存在` })
      }
      if (identityCard) {
        const count = await dbm.collection(collectionName).countDocuments({ identityCard, classId })
        if (count) return cloud.utils.requestReturn({ code: 500, msg: `身份证号${identityCard}已存在` })
      }
      //给线下学员导入的表添加
      let res = await cloud.nw.db.add({
        dbName: collectionName,
        dataJson: element,
        cancelAddTime: false
      });
      await cloud.nw.db.add({
        dbName,
        dataJson: {
          classId,
          offlineUserId: res,
          source: "file",
          userState: 1,
          userName: element.name,
          userPinyin: element.userPinyin
        },
        cancelAddTime: false
      });
    }
    return cloud.utils.requestReturn({ data: "" })
  }

  async function queryNotSuspended() {
    const count = await dbm.collection(dbName).countDocuments({ classId: data.classId, userState: 1 })
    return cloud.utils.requestReturn({ data: count })
  }

  async function scoreImport() {
    let { classId, list } = data
    let docx = await dbm.collection(dbName).find({ classId }).project({ userName: 1, declarationBatchNumber: 1, userId: 1 }).toArray()

    let errorList = []
    for (let index = 0; index < list.length; index++) {
      const element = list[index];
      let res = await cloud.nw.db.findByWhereJson({
        dbName: "web-users",
        whereJson: { "baseInfo.identityCard": element.idCard.trim() },
        sortArr: [{ "name": "_add_time", "type": "desc" }],
      });
      if (res && res._id) {
        console.log("docx", docx, res._id)
        let current = cloud.utils.findIndexByField(docx, "userId", res._id)
        if (current == -1) return cloud.utils.requestReturn({ code: 500, msg: `学员${res.baseInfo.name}不存在于班级` })
        if (!docx[current].declarationBatchNumber && (element.theory || element.practicalTraining)) return cloud.utils.requestReturn({ code: 500, msg: `学员${res.baseInfo.name}请先申报批次号` })

        //“理论” ≥60 或 合格 或 良好 或 优秀，并且，“实训” ≥60 或 合格 或 良好 或 优秀，显示【获证】，反之 显示 【未获证】
        let isExamination = null //获证情况默认未获证
        //isExamination 0.未获证 1.获证  2.缺考 
        if (element.theory || element.practicalTraining) {
          if (getGrade(element.theory) && getGrade(element.practicalTraining)) {
            isExamination = 1
          } else {
            isExamination = 0
          }
        }

        if ((element.theory == "缺考") || (element.practicalTraining == "缺考")) isExamination = 2
        console.log(isExamination, element.theory, element.practicalTraining)
        await cloud.nw.db.update({
          dbName,
          whereJson: { classId, userId: res._id },
          dataJson: { isExamination, theory: element.theory, practicalTraining: element.practicalTraining }
        });
      } else {
        element.error = "学员不存在"
        errorList.push(element)
      }
    }
    return cloud.utils.requestReturn({ data: { errorList } })

    function getGrade(score) {
      if (isNumericStringUsingParseFloat(score) && Number(score) >= 60) {
        return true
      } else if (['合格', '良好', '优秀'].includes(score)) {
        return true
      } else {
        return false
      }
      function isNumericStringUsingParseFloat(str) {
        const num = parseFloat(str);
        return typeof num === "number" && num.toString() === str;
      }
    }
  }

  //是否可以挪动到别的班级
  async function canMoveOtherClass() {
    let list = []
    let classIds = ""
    for (let index = 0; index < data.length; index++) {
      const element = data[index];
      let { classId, userId } = await cloud.nw.db.findByWhereJson({
        dbName, whereJson: { _id: element },
      });
      classIds = classId
      let aa = await db.collection("admin-class-signIn").find({ classId, userId }).project({ status: 1 }).toArray()
      if (aa && aa.length) {
        let res = await cloud.nw.db.findByWhereJson({
          dbName: "web-users", whereJson: { _id: userId },
        });
        list.push(res.baseInfo.name)
      }
    }
    //班级调班的逻辑，已经被点名过，是不能挪，除非是结业了
    let { status } = await cloud.nw.db.findByWhereJson({
      dbName: "admin-class",
      whereJson: { _id: classIds },
    });
    if (status == 2) {
      return cloud.utils.requestReturn({ data: "" })
    } else if (list.length) {
      return cloud.utils.requestReturn({ code: 500, msg: `${list.toString()}已被点名过，不能挪动到别的班级` })
    } else {
      return cloud.utils.requestReturn({ data: "" })
    }
  }

  async function add() {
    let res = await cloud.nw.db.findByWhereJson({
      dbName,
      whereJson: {
        classId: data.classId, //班级id
        userId: data.userId //学员id
      }
    });
    if (res && res._id) {
      let ret = await cloud.nw.db.findByWhereJson({
        dbName: "web-users",
        whereJson: { _id: data.userId }
      });
      return cloud.utils.requestReturn({ msg: `该班级已存在学员${ret.baseInfo.name}`, code: 500 })
    } else {
      await cloud.utils.addData(dbName, data)
      setStudentData()
      return cloud.utils.requestReturn({ data: "添加成功" })
    }
  }

  //班次有几个未停课的学生
  async function classStudentCount() {
    let array = await dbm.collection(dbName).find({ classId: data.classId }).toArray()
    let { date } = await cloud.nw.db.findByWhereJson({
      dbName: "admin-teaching-schedule",
      whereJson: { _id: data.schedulingId },
    });
    let arr = []
    array.forEach(element => {
      if (element.userState == 1) {
        arr.push(element.userId)
      } else {
        //时间戳
        let dateStamp = cloud.utils.getTimeFn(date)
        let suspensionClassDateStamp = cloud.utils.getTimeFn(element.suspensionClassDate)
        if (suspensionClassDateStamp > dateStamp) {
          arr.push(element.userId)
        }
      }
    });
    //该班级未停课的学生数量
    return cloud.utils.requestReturn({ data: arr.length })
  }

  async function otherClass() {
    let obj = {
      _id: { $ne: data.classId },
      //curriculumId: data.curriculumId
    }
    let aa = await dbm.collection("admin-class").find(obj).toArray()
    return cloud.utils.requestReturn({ data: aa })
  }

  //查询学员信息不分页
  async function query() {
    let aa = await dbm.collection(dbName).find({ classId: data.classId }).toArray()
    return cloud.utils.requestReturn({ data: aa })
  }

  //修改学员信息
  async function setStudentData() {
    let aa = await dbm.collection(dbName).find({ classId: data.classId }).toArray()
    for (let index = 0; index < aa.length; index++) {
      const element = aa[index];
      if (!element.userName) { //如果没有姓名
        let res = await cloud.nw.db.findByWhereJson({
          dbName: "web-users",
          whereJson: { _id: element.userId },
        });
        await cloud.nw.db.update({
          dbName,
          whereJson: { _id: element._id },
          dataJson: { userName: res.baseInfo.name }
        });
      }
      if (element.userName && !element.userPinyin) {
        await cloud.nw.db.update({
          dbName,
          whereJson: { _id: element._id },
          dataJson: { userPinyin: pinyin(element.userName, { toneType: "none" }) }
        });
      }
    }
  }

  //学员列表
  async function list() {
    let whereJson = { ...data }
    delete whereJson.pageIndex
    delete whereJson.pageSize
    delete whereJson.keyWords
    delete whereJson.keyWords
    delete whereJson.affiliation
    delete whereJson.sort
    //则表示查询的是线上学员，不包含线下
    if (data.screen && data.screen == 1) {
      whereJson.userId = { $exists: true }
    }
    //报名所属
    if (data.affiliation && data.affiliation.length) {
      whereJson["affiliation"] = { $in: data.affiliation }
    }
    if (data.keyWords) {
      let mobiles = []
      //如果是数字
      let query = {}
      let key
      if (cloud.utils.isNumber(data.keyWords)) {
        key = "mobile"
      } else {
        key = "approvalContent.model.name"
      }
      //模糊搜索
      query[key] = db.RegExp({ regexp: data.keyWords, options: 'i' })

      let orders = await dbm.collection("web-order").find(query).toArray()
      orders.forEach(element => {
        mobiles.push(element._id)
      });
      whereJson["orderId"] = { $in: mobiles }
    }

    let res = await cloud.nw.db.selects({
      dbName,
      getCount: true,
      pageIndex: data.pageIndex,
      pageSize: data.pageSize,
      // 主表 where 条件
      whereJson,
      // 主表排序规则
      sortArr: [
        { "name": "userState", "type": "desc" },
        { "name": data.sort, 'type': "asc" },
        { "name": "_add_time", "type": "asc" }
      ],
      // 副表列表
      foreignDB: [
        {
          dbName: "web-order",//副表 order
          localKey: "orderId",
          foreignKey: "_id",
          as: "order_Info",
          limit: 1,
          // 副表字段显示规则
          fieldJson: {
            status: 1,
            rejectMsg: 1,
            displayPrice: 1,
            orderUserInfo: 1,
            pay_info: 1,
            out_trade_no: 1,
            mobile: 1
          },
        },
        {
          dbName: "web-users",//副表 order
          localKey: "userId",
          foreignKey: "_id",
          as: "user_Info",
          limit: 1,
          // 副表字段显示规则
          fieldJson: {
            baseInfo: 1
          },
        },
        {
          dbName: "admin-class-offline-student",//线下学员
          localKey: "offlineUserId",
          foreignKey: "_id",
          as: "user_data",
          limit: 1,
        },
        {
          dbName: "admin-class-signIn",//签到记录
          localKey: "userId",
          foreignKey: "userId",
          as: "signIn_data",
          limit: 100,
          whereJson: {
            status: 1,
            classId: data.classId
          },
        },
      ]
    });
    return cloud.utils.requestReturn({ data: res })
  }


  //新增学员进行筛选
  async function orders() {
    let whereJson = {}
    let mobiles = []
    let noRequireOrders = []  //不符合要求的订单
    //未结束的订单 || 付款时间是传入年份的订单
    let withinScopeOrders = []
    let isSearchMobile = false
    if (data.curriculumId) whereJson["curriculum_id"] = data.curriculumId

    if (data.status && data.status.length) {
      whereJson["status"] = { $in: data.status }
    }

    //待开班和开班的班级学员不能被选中
    let aa = await dbm.collection("admin-class").find({ status: { $in: [0, 1] } }).toArray()
    let bb = []  //查出哪些班级是开班||待开班
    aa.forEach(element => { bb.push(element._id) });
    let cc = await dbm.collection("admin-class-student").find({ classId: { $in: bb } }).toArray()
    cc.forEach(element => { noRequireOrders.push(element.orderId) });

    //如果有时间筛选
    if (data.year) {
      //判断是否有挪至次年的标记，有的话是否等于传入的年份
      let aa = await dbm.collection("web-order").find({
        statisticsYear: {
          $exists: true,   // 判断属性存在[1,2](@ref)
          $eq: data.year        // 验证值等于2025[5](@ref)
        }
      }).project({ _id: 1 }).toArray()

      //没有标记，正常筛选
      let timeobj = {
        _add_time_str: { $regex: data.year.toString(), $options: "i" },
        statisticsYear: { $exists: false }
      }
      let bb = await dbm.collection("web-order").find(timeobj).project({ _id: 1 }).toArray()

      let cc = [...aa, ...bb]
      cc.forEach(element => {
        withinScopeOrders.push(element._id)
      });
    }

    let okOrders = []  //符合要求的订单
    withinScopeOrders.forEach(element => {
      if (!noRequireOrders.includes(element)) okOrders.push(element)
    });
    if (okOrders.length) {
      whereJson["_id"] = { $in: okOrders }
    } else if (noRequireOrders.length) {
      whereJson["_id"] = { $nin: noRequireOrders }
    }

    //如果有学生来源筛选
    if (data.hasOwnProperty('studentSourceList') && data.studentSourceList.length) {
      isSearchMobile = true
      let obj = {
        "baseInfo.studentSourceList.source": { $in: data.studentSourceList }
      }
      let users = await dbm.collection("web-users").find(obj).toArray()
      users.forEach(element => {
        mobiles.push(element.mobile)
      });
    }

    //报名所属
    if (data.affiliation && data.affiliation.length) {
      whereJson["approvalContent.model.affiliation"] = { $in: data.affiliation }
    }

    let params = ['name', 'mobile', "identityCard", 'enterprise']
    params.forEach(element => {
      if (data.hasOwnProperty(element) && data[element]) {
        whereJson[`approvalContent.model.${element}`] = { $regex: data[element] }
      }
    });

    //如果涉及到手机号查询，则需要把手机号加入查询条件
    if (isSearchMobile) whereJson["mobile"] = { $in: mobiles }

    console.log("whereJson入参-新增学员", whereJson)

    let res = await cloud.nw.db.selects({
      dbName: "web-order",
      getCount: true,
      pageIndex: data.pageIndex,
      pageSize: data.pageSize,
      whereJson,
      sortArr: [{ "name": "_add_time", "type": "desc" }],
      foreignDB: [
        {
          dbName: "web-course",//副表 order
          localKey: "curriculum_id", //主表外键名
          foreignKey: "_id", //副表外键名
          as: "curriculum_Info", //副表连表结果的别名
          limit: 1,
          // 副表字段显示规则
          fieldJson: {
            name: true,
          },
        },
        {
          dbName: "web-users",//副表 order
          localKey: "userId", //主表外键名
          foreignKey: "_id", //副表外键名
          as: "user_Info", //副表连表结果的别名
          limit: 1,
          // 副表字段显示规则
          fieldJson: {
            studentSourceList: true,
          },
        },
      ]
    });

    return cloud.utils.requestReturn({ data: res })
  }
}
